import 'package:flutter_app/app/models/download.dart';
import 'package:nylo_framework/nylo_framework.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'db_provider.dart';
import 'package:sqflite/sqflite.dart';

class DownloaderProvider implements NyProvider {
  // 下载数据库提供者
  final DbProvider _dbProvider = DbProvider();
  Future<Database> get database async => await _dbProvider.database;

  @override
  boot(Nylo nylo) async {
    // boot your provider
    // ...
    await initialize();

    return nylo;
  }

  @override
  afterBoot(Nylo nylo) async {
    // Called after Nylo has finished booting
    // ...
  }

  Future<void> initialize() async {
    await FlutterDownloader.initialize(debug: true, ignoreSsl: true);

    FlutterDownloader.registerCallback(downloadCallback);

    // 每次启动，取消任务管理里的任务，将数据库中的数据标记为暂停
    await syncTask();
  }

  syncTask() async {
    await FlutterDownloader.cancelAll();
    var db = await database;
    await db.update(
      _dbProvider.downloadsTable,
      {"status": DownloadStatusPaused},
      where: "status = ?",
      whereArgs: [DownloadStatusDownloading],
    );
  }

  @pragma('vm:entry-point')
  static void downloadCallback(String id, int status, int progress) {}
}
